<?php
	
	function new_user($data, $return_id){
			$prefix = "timetable_";
		
			$user_name = $data['client_name'];
			$user_fullname = $data['client_fullname'];
			$user_password = $data['client_password'];
			$user_password2 = $data['client_password2'];
			$user_email = $data['client_email'];
			$role_status = $data['role'];
			
			if($role_status == '') {
				$role_status = 5;
			}

			$user_id = username_exists( $user_name );
	
			global $wpdb;
			//echo "register <br>";

			//echo json_encode($data);

			if ( !$user_id and email_exists($user_email) == false and $user_password == $user_password2 ) {
				//echo "<hr> new  <br>";

				//$random_password = wp_generate_password( $length=12, $include_standard_special_chars=false );
				//$wp_user_id = wp_create_user( $user_name, $user_password, $user_email );
				$wp_user_id = wp_insert_user( 
						array(
							"user_login" => $user_name, 
							"user_pass" => $user_password, 
							"display_name" => $user_fullname, 
							"user_email" => $user_email)
					);


	
				//echo $wp_user_id . "<br>";

				$role_query = "SELECT idrole role_id,  role_name, role_status FROM {$prefix}role WHERE role_status = $role_status";
				$role = $wpdb->get_row($role_query, ARRAY_A);	
				$role_id = $role['role_id'];
				
				//echo $role_id . "<br>";
				
				$wpdb->insert(
						"${prefix}user",
						array(
								"role_id"=> $role_id,
								"wp_user_id" =>$wp_user_id
							),
						array(
								'%d',
								'%d'
							)
					);
				
				$user_id =  $wpdb->insert_id;
				//echo $user_id . "<br>";


				$res = '';

				if($role_status == 1){

				}elseif($role_status == 5){
					$wpdb->insert(
						"{$prefix}client",
						array(
								"client_name"=> $user_fullname,
								"user_id" =>$user_id
							),
						array(
								'%s',
								'%d'
							)
					);
					$_id =  $wpdb->insert_id;
					$sql = "SELECT idclient client_id, client_name, client_contact FROM {$prefix}client WHERE idclient = $_id";
					$res = $wpdb->get_row($sql, ARRAY_A);

					/*$file = __DIR__."/out/log";
					$str_put = json_encode($res);
					file_put_contents($file, $str_put, FILE_APPEND | LOCK_EX);*/


				}elseif($role_status == 3){
					//echo "teacher";
					$wpdb->insert(
						"{$prefix}teacher",
						array(
								"teacher_name"=> $user_fullname,
								"user_id" =>$user_id
							),
						array(
								'%s',
								'%d'
							)
					);
					$res =  $wpdb->insert_id;
				}

				if(isset($return_id)){
					return $res;
				}else{
					echo json_encode(array("res"=>$res));
				}
			}
	}

?>